package me.zhengjie.poemQuestions.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.poemQuestions.domain.PoemQuestions;
import me.zhengjie.poemQuestions.mapper.PoemQuestionsMapper;
import me.zhengjie.poemQuestions.mapper.UserAnswerRecordMapper;
import me.zhengjie.poemQuestions.service.PoemQuestionsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class PoemQuestionsServiceImpl extends ServiceImpl<PoemQuestionsMapper, PoemQuestions>
        implements PoemQuestionsService {

    private final UserAnswerRecordMapper userAnswerRecordMapper;

    public PoemQuestionsServiceImpl(UserAnswerRecordMapper userAnswerRecordMapper) {
        this.userAnswerRecordMapper = userAnswerRecordMapper;
    }


    @Override
    public PoemQuestions getRandomQuestion() {
        return baseMapper.getRandomQuestion();
    }



    @Override
        public List<PoemQuestions> recommendWeakQuestions(Integer userId, int limitPerCategory, int categoryLimit) {
            List<PoemQuestions> recommendations = new ArrayList<>();
            List<String> weakCategories = userAnswerRecordMapper.findWeakCategories(userId, categoryLimit);
            for (String category : weakCategories) {
                recommendations.addAll(userAnswerRecordMapper.recommendFromCategory(category, limitPerCategory));
            }
            return recommendations;
        }

    @Override
    @Transactional(readOnly = true)
    public PoemQuestions getRandomQuestionForUser(Integer userId) {
        // 1. 当日是否已答题
        int todayCount = baseMapper.countTodayAnswers(userId);
        if (todayCount > 0) {
            throw new IllegalStateException("您今日已答题，明天再来挑战吧！");
        }
        // 2. 随机取一道未答过的题
        PoemQuestions question = baseMapper.getRandomUnansweredQuestion(userId);
        if (question == null) {
            throw new IllegalStateException("您已完成所有题目！");
        }
        return question;
    }
}
